package com.zhike.component;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import lombok.extern.slf4j.Slf4j;

import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;

@Component
@Slf4j
public class MyElasticsearchClient {

    @Value("${spring.elasticsearch.uris}")
    private String uri;

    @Value("${spring.elasticsearch.username}")
    private String username;

    @Value("${spring.elasticsearch.password}")
    private String password;

    // private HttpHost[] getHttpHosts() {
    // HttpHost[] hhs = new HttpHost[uris.length];
    // for (int i = 0; i < uris.length; i++) {
    // hhs[i] = HttpHost.create(uris[i]);
    // }
    // return hhs;
    // }

    public RestClient getRestClient() {
        // 使用 HttpHost 创建 RestClientBuilder 实例
        RestClient restClient = RestClient.builder(HttpHost.create(uri))
                .setHttpClientConfigCallback(httpClientBuilder -> {
                    // 设置认证信息
                    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                    credentialsProvider.setCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(username, password));
                    return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                })
                .build();
        return restClient;
    }

    public ElasticsearchClient getElasticsearchClient() {
        RestClient restClient = getRestClient();
        try {
            // 创建 Elasticsearch 传输层
            ElasticsearchTransport transport = new RestClientTransport(
                    restClient, new JacksonJsonpMapper());
            // 创建 Elasticsearch 客户端
            return new ElasticsearchClient(transport);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // try {
            // restClient.close();
            // } catch (Exception e) {
            // e.printStackTrace();
            // }
        }
        return null;
    }
}
